package xyz.canran.project.algorithm.rate.limiter;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 固定窗口 限流器 （即计数器限流）
 */
public class SimpleWindowRateLimiter {

    private int qps;
    private long timeWindows;
    private AtomicInteger counter;
    private long startTime;

    public SimpleWindowRateLimiter() {
        this.qps = 10;
        this.timeWindows = 1000;
        this.counter = new AtomicInteger(0);
        this.startTime = System.currentTimeMillis();
    }

    public SimpleWindowRateLimiter(int qps, long timeWindows) {
        this.qps = qps;
        this.timeWindows = timeWindows;
        this.counter = new AtomicInteger(0);
        this.startTime = System.currentTimeMillis();
    }

    public synchronized boolean tryAcquire() {
        if ((System.currentTimeMillis() - startTime) > timeWindows) {
            counter.set(0);
            startTime = System.currentTimeMillis();
        }
        return counter.incrementAndGet() <= qps;
    }
}
